package com.zmcn.fileTransfer.business.filetransfer.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;

import com.zmcn.fileTransfer.business.filetransfer.service.FileTransferService;
import com.zmcn.fileTransfer.business.filetransfer.vo.FileInfoVO;
import com.zmcn.fileTransfer.fw.util.AESCoder;
import com.zmcn.fileTransfer.fw.util.RandUtil;
import com.zmcn.fileTransfer.fw.util.SecurityUtil3;

/**
 * 
 * 文件传输业务接口实现
 * 
 * @author <b>欧建东<br/>
 *         Email:oyjd@163.com</b>
 * @version 1.0
 */
public class FileTransferServiceImpl implements FileTransferService {
	/**
	 * 设置需要获取的文件目录
	 */
	private String readPath;
	/**
	 * 帐号
	 */
	private String account;
	/**
	 * 密码
	 */
	private String pwd;

	/**
	 * 数据流密匙
	 */
	private Key key;

	public void setAccount(String account) {
		this.account = account;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setReadPath(String readPath) {
		this.readPath = readPath;
	}

	public void setFlowPwd(String flowPwd) {
		key = AESCoder.toKey(AESCoder.strToByte(flowPwd));
	}

	/**
	 * 获取文件信息
	 * 
	 * @return
	 */
	public List<FileInfoVO> getFileInfo() {
		List<FileInfoVO> result = new ArrayList<FileInfoVO>();
		File ff = new File(readPath);
		for (File f : ff.listFiles()) {
			if (f.isFile()) {
				// 文件最后修改小于30分钟的不传递,避免大文件正在拷贝的时候被同步传输
				if (System.currentTimeMillis() - f.lastModified() < 1800000) {
					System.out.println(f.getName());
					continue;
				}
				String name = f.getName();
				int pos = name.lastIndexOf(".");
				FileInfoVO vo = new FileInfoVO();
				vo.setFileSize(f.length());
				vo.setFileName(name.substring(0, pos));
				vo.setFileEx(name.substring(pos + 1));
				result.add(vo);
			}
		}
		return result;
	}

	/**
	 * 读取文件特定切片的字节流
	 * 
	 * @param fileName
	 *            文件名
	 * @param size
	 *            文件切片大小
	 * @param batch
	 *            第几切片
	 * @return
	 */
	public byte[] readFile(String fileName, int size, int batch) {
		try {
			File f = new File(readPath + File.separator + fileName);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream fis = new FileInputStream(f);
			byte[] b = new byte[1024];
			int pos = -1;
			if (0 == batch) {
				while (-1 != (pos = fis.read(b))) {
					baos.write(b, 0, pos);
				}
			} else {
				int count = 0;
				fis.skip((batch - 1) * size);
				while (-1 != (pos = fis.read(b))) {
					count += pos;
					if (count < size) {
						baos.write(b, 0, pos);
					} else if (count == size) {
						baos.write(b, 0, pos);
						break;
					} else {
						baos.write(b, 0, b.length - (count - size));
						break;
					}
				}
			}
			byte[] all = baos.toByteArray();
			fis.close();
			baos.close();
			return AESCoder.encrypt(all, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 验证帐号密码
	 * 
	 * @param s
	 * @param pwd
	 * @return
	 */
	public boolean checkToken(String s) {
		boolean result = false;
		try {
			String s1 = SecurityUtil3.decrypt(s);
			StringBuffer sb = new StringBuffer();
			for (int i = 1; i < s1.length(); i += 2) {
				sb.append(s1.charAt(i));
			}
			String tmp = sb.toString();
			String[] ss = tmp.split("--!--");
			if (ss.length == 3) {
				// long a = Long.parseLong(ss[2]);
				// long b = System.currentTimeMillis() - a;
				// if (b <= 600000L && b >= -600000L) {// 10分钟内
				if (this.account.equals(ss[0]) && this.pwd.equals(ss[1])) {
					result = true;
				} else {
					System.out.println("帐号密码不正确");
				}
				// } else {
				// System.out.println("密码时差超过10分钟");
				// }
			}
		} catch (Exception err) {
			System.out.println("验证密码异常：" + err.getMessage());
		}
		return result;
	}

	/**
	 * 获取token
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getToken() {
		String result = "";
		try {
			String s = account + "--!--" + pwd + "--!--" + System.currentTimeMillis();
			String s1 = RandUtil.get(s.length());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < s.length(); i++) {
				sb.append(s1.charAt(i)).append(s.charAt(i));
			}
			result = SecurityUtil3.encrypt(sb.toString());
		} catch (Exception err) {
			err.printStackTrace();
		}
		return result;
	}

	/**
	 * 切割文件份数
	 * 
	 * @param len
	 * @param size
	 * @return
	 */
	public int splitFile(long len, int size) {
		Long t = 0L;
		if (len % size == 0) {
			t = len / size;
		} else {
			t = len / size + 1;
		}
		return t.intValue();
	}

	// public static void main(String[] args) throws Exception {
	// FileTransferServiceImpl s = new FileTransferServiceImpl();
	// s.setPath("D:");
	// s.setSize(1024 * 1024);
	// int n = s.split(new File("D:/My.jar").length());
	// System.out.println(n);
	// OutputStream baos = new FileOutputStream(new File("D:/My2.jar"));
	// for (int i = 1; i <= n; i++) {
	// byte[] b = s.readFile("My.jar", i);
	// baos.write(b);
	// }
	// baos.close();

	// s.setAccount("1234");
	// s.setPwd("abcd");
	// String a = s.getToken();
	//
	// System.out.println(s.checkToken(a));
	// }
}
